<template>
  <div id="calender"></div>
</template>

<script lang="ts" setup>
import "@fullcalendar/core/vdom"; //vite 中需要引入
import { Calendar, EventClickArg, EventContentArg } from "@fullcalendar/core";
import daygrid from "@fullcalendar/daygrid";
import interaction, { DateClickArg } from "@fullcalendar/interaction";
import { EventItem } from "./types";
import { onMounted, ref, PropType, watch } from "vue";
let props = defineProps({
  // 语言
  local: {
    type: String,
    default: "zh-cn",
  },
  // 视图模式
  initalView: {
    type: String,
    default: "dayGridMonth",
  },
  // 日历上方按钮文字
  buttonText: {
    type: Object,
    default: () => {
      return {
        today: "今天",
        month: "月",
        week: "周",
        day: "日",
        prevYear: "上一年",
        nextYear: "下一年",
        prev: "上一月",
        next: "下一月",
      };
    },
  },
  // 头部工具栏
  headerToolbar: {
    type: Object,
    default: () => {
      return {
        start: "title",
        center: "",
        end: "prev today next",
      };
    },
  },
  // 底部工具栏
  footerToolbar: {
    type: Object,
    default: () => {
      return {};
    },
  },
  // 事件源
  events: {
    type: Array as PropType<EventItem[]>,
    default: () => [],
  },
  // 日历显示结束时间
  displayEventEnd: {
    type: Boolean,
    default: true,
  },
  // 渲染自定义内容
  eventContent: {
    type: Function,
  },
});

//分发事件
let emits = defineEmits(["dateClick", "eventClick"]);

// 日历实例
let calender = ref<Calendar>();
// 渲染日历的方法
let renderCalender = () => {
  let el = document.getElementById("calender");
  if (el) {
    calender.value = new Calendar(el, {
      // 日历插件
      locale: props.local,
      plugins: [daygrid, interaction],
      initialView: props.initalView,
      buttonText: props.buttonText,
      headerToolbar: props.headerToolbar,
      footerToolbar: props.footerToolbar,
      eventSources: [
        {
          events(e, callback) {
            if (props.events.length) {
              callback(props.events);
            } else {
              callback([]);
            }
          },
        },
      ],
      // 点击日历上得某一天
      dateClick(info: DateClickArg) {
        emits("dateClick", info);
      },
      // 点击自定义日历事件时触发
      eventClick(info: EventClickArg) {
        emits("eventClick", info);
      },
      displayEventEnd: props.displayEventEnd,
      // 渲染自定义内容
      eventContent:props.eventContent
    });
    calender.value.render();
  }
};

onMounted(() => {
  renderCalender();
});

// 监听父组件传递的事件源
watch(
  () => props.events,
  () => {
    renderCalender();
  },
  {
    deep: true,
  }
);
</script>
<style lang="scss" scoped></style>
